package net.joneepenk.util.jdbc;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

public abstract class JdbcParamHandler {
	
	private static Map<Class<?>, JdbcParamHandler> holder = null;
	
	public abstract void setParam(PreparedStatement ps, int index, Object param) throws SQLException;
	
	public static JdbcParamHandler getInstance(Class<?> clazz){
		if(holder == null){
			holder = new HashMap<Class<?>, JdbcParamHandler>();
			holder.put(Boolean.class, new BooleanHandler());
			holder.put(Integer.class, new IntegerHandler());
			holder.put(Long.class, new LongHandler());
			holder.put(BigDecimal.class, new BigDecimalHandler());
			holder.put(String.class, new StringHandler());
			holder.put(Timestamp.class, new TimestampHandler());
			holder.put(Object.class, new ObjectHandler());
		}
		return holder.get(clazz);
	}

	private static class BooleanHandler extends JdbcParamHandler{
		public void setParam(PreparedStatement ps, int index, Object param) throws SQLException {
			ps.setBoolean(index, (Boolean) param);
		}
	}

	private static class IntegerHandler extends JdbcParamHandler{
		public void setParam(PreparedStatement ps, int index, Object param) throws SQLException {
			ps.setInt(index, (Integer) param);
		}
	}

	private static class LongHandler extends JdbcParamHandler{
		public void setParam(PreparedStatement ps, int index, Object param) throws SQLException {
			ps.setLong(index, (Long) param);
		}
	}
	
	private static class BigDecimalHandler extends JdbcParamHandler{
		public void setParam(PreparedStatement ps, int index, Object param) throws SQLException {
			ps.setBigDecimal(index, (BigDecimal) param);
		}
	}
	
	private static class StringHandler extends JdbcParamHandler{
		public void setParam(PreparedStatement ps, int index, Object param) throws SQLException {
			ps.setString(index, (String) param);
		}
	}
	
	private static class TimestampHandler extends JdbcParamHandler{
		public void setParam(PreparedStatement ps, int index, Object param) throws SQLException {
			ps.setTimestamp(index, (Timestamp) param);
		}
	}
	
	private static class ObjectHandler extends JdbcParamHandler{
		public void setParam(PreparedStatement ps, int index, Object param) throws SQLException {
			ps.setObject(index, param);
		}
	}

}
